package com.wyc.serviceMap.remote;

import com.wyc.internalCommon.constant.AmapConfigConstant;
import com.wyc.internalCommon.response.ServiceResponse;
import com.wyc.internalCommon.response.TerminalResponse;
import com.wyc.internalCommon.response.TrSearchResponse;
import com.wyc.internalCommon.result.ApiResult;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.List;

/**
 * 终端api
 */
@Service
public class TerminalClient {

    @Value("${amap.key}")
    private String amapKey;

    @Value("${amap.sid}")
    private String amapSid;

    @Autowired
    private RestTemplate restTemplate;

    /**
     * 添加终端
     * @param name
     * @return
     */
    public ApiResult add(String name,String carId){
        // 拼接路径url
        StringBuilder urlBuilder = new StringBuilder();
        urlBuilder.append(AmapConfigConstant.TERMIANAL_ADD_URL_PREFIX);
        urlBuilder.append("?");
        urlBuilder.append("key="+amapKey);
        urlBuilder.append("&");
        urlBuilder.append("sid="+amapSid);
        urlBuilder.append("&");
        urlBuilder.append("name="+name);
        urlBuilder.append("&");
        urlBuilder.append("desc="+carId);

        ResponseEntity<String> responseEntity = restTemplate.postForEntity(urlBuilder.toString(), null, String.class);
        String body = responseEntity.getBody();
        JSONObject jsonObject = JSONObject.fromObject(body);
        JSONObject data = jsonObject.getJSONObject("data");
        String tid = data.getString("tid");

        TerminalResponse terminalResponse = new TerminalResponse();
        terminalResponse.setTid(tid);

        return ApiResult.success(terminalResponse);

    }


    /**
     * 搜索终端(周边搜索)
     * @param center
     * @param radius
     * @return
     */
    public ApiResult aroundSearch(String center,Integer radius){
        // 拼接路径url
        StringBuilder urlBuilder = new StringBuilder();
        urlBuilder.append(AmapConfigConstant.TRACK_TERMIANAL_AROUND_SEARCH);
        urlBuilder.append("?");
        urlBuilder.append("key="+amapKey);
        urlBuilder.append("&");
        urlBuilder.append("sid="+amapSid);
        urlBuilder.append("&");
        urlBuilder.append("center="+center);
        urlBuilder.append("&");
        urlBuilder.append("radius="+radius);

        ResponseEntity<String> responseEntity = restTemplate.postForEntity(urlBuilder.toString(), null, String.class);
        String body = responseEntity.getBody();
        JSONObject jsonObject = JSONObject.fromObject(body);
        JSONObject data = jsonObject.getJSONObject("data");
        JSONArray results = data.getJSONArray("results");
        List<TerminalResponse> list = new ArrayList<>();
        if (results.size() > 0){
            for (int i = 0; i < results.size(); i++) {
                TerminalResponse terminalResponse = new TerminalResponse();
                JSONObject resultJSONObject = results.getJSONObject(i);
                String tid = resultJSONObject.getString("tid");
                terminalResponse.setTid(tid);
                // getLong 会丢失精度，采用Long.parseLong(str);
                String carIdStr = resultJSONObject.getString("desc");
                Long carId = Long.parseLong(carIdStr);
                terminalResponse.setCarId(carId);

                // 经纬度等信息
                JSONObject location = resultJSONObject.getJSONObject("location");
                // 经度
                String  longitude = location.getString("longitude");
                // 纬度
                String latitude = location.getString("latitude");
                // 到中心点的距离
                int distance = location.getInt("distance");
                terminalResponse.setLongitude(longitude);
                terminalResponse.setLatitude(latitude);
                terminalResponse.setDistance(distance);

                list.add(terminalResponse);
            }
        }


        return ApiResult.success(list);

    }

    /**
     * 查询轨迹信息
     * @param tid 终端id
     * @param starttime 开始时间，Unix时间戳（轨迹点的定位时间）,需要精准到毫秒
     * @param endtime   结束时间，Unix时间戳（轨迹点的定位时间）,需要精准到毫秒
     * 结束时间不能大于当前时间，且距离开始时间不能超过24小时。
     * 若轨迹较多，建议将时间段进行拆分。
     * @return
     */
    public ApiResult<TrSearchResponse> trsearch(String tid, Long starttime, Long endtime){
        // 拼接路径url
        StringBuilder urlBuilder = new StringBuilder();
        urlBuilder.append(AmapConfigConstant.TRACK_TERMIANAL_TRSEARCH);
        urlBuilder.append("?");
        urlBuilder.append("key="+amapKey);
        urlBuilder.append("&");
        urlBuilder.append("sid="+amapSid);
        urlBuilder.append("&");
        urlBuilder.append("tid="+tid);
        urlBuilder.append("&");
        urlBuilder.append("starttime="+starttime);
        urlBuilder.append("&");
        urlBuilder.append("endtime="+endtime);

        ResponseEntity<String> responseEntity = restTemplate.getForEntity(urlBuilder.toString(), String.class);
        JSONObject result = JSONObject.fromObject(responseEntity.getBody());
        JSONObject data = result.getJSONObject("data");
        int counts = data.getInt("counts");
        if (counts == 0){
            return null;
        }

        TrSearchResponse trSearchResponse = new TrSearchResponse();
        JSONArray tracks = data.getJSONArray("tracks");
        for (int i = 0; i < tracks.size(); i++) {
            JSONObject track = tracks.getJSONObject(i);
            // 轨迹长度，单位：米
            long distance = track.getLong("distance");
            trSearchResponse.setDriveMile(distance);
            // 轨迹持续时间，单位：毫秒
            long time = track.getLong("time");
            Long driveTime = time/ (60 * 1000);
            trSearchResponse.setDriveTime(driveTime);
        }

        return ApiResult.success(trSearchResponse);

    }

}
